import {
  fetchData,
  fetchDataPromice,
  fetchDataPromiceError,
} from "./fetchData";

test("fetchData test", (done) => {
  fetchData((data) => {
    expect(data).toEqual({
      code: 1,
      data: "success",
      message: "成功",
    });
    // 必须添加 done()，才可使接口完全返回后测试
    done();
  });
});

// 直接返回 Promice
test("fetchDataPromice test", () => {
  // 必须加 return
  return fetchDataPromice().then((response) => {
    expect(response.data).toEqual({
      code: 1,
      data: "success",
      message: "成功",
    });
  });
});

// async await
test("fetchDataPromice test", async () => {
  // toMatchObject() 匹配对象属性的子集
  await expect(fetchDataPromice()).resolves.toMatchObject({
    data: { data: "success" },
  });
});
test("fetchDataPromice test", async () => {
  const response = await fetchDataPromice();
  expect(response.data).toMatchObject({ data: "success" });
});

// 捕获错误
test("fetchDataPromiceError test", () => {
  // 断言 必须执行一次 expect
  expect.assertions(1);
  return fetchDataPromiceError().catch((e) => {
    expect(e.toString().indexOf("Network Error") > -1).toBe(true);
  });
});
